package fi.internetix.quercus;

import java.io.BufferedReader;
import java.io.Reader;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.caucho.quercus.QuercusContext;
import com.caucho.quercus.env.NullValue;
import com.caucho.quercus.env.Value;
import com.caucho.quercus.page.QuercusPage;
import com.caucho.util.Log;
import com.caucho.vfs.WriteStream;
import com.google.cloud.sql.jdbc.internal.ClientSideClob;

public class GoogleEnv extends com.caucho.quercus.env.GoogleEnv {
  
  private static final Logger log = Log.open(GoogleEnv.class);

  public GoogleEnv(QuercusContext quercus, QuercusPage page, WriteStream out, HttpServletRequest request, HttpServletResponse response) {
    super(quercus, page, out, request, response);
  }

  public GoogleEnv(QuercusContext quercus) {
    super(quercus);
  }

  @Override
  public Value wrapJava(Object obj) {
    if (obj instanceof ClientSideClob) {
      try {
        ClientSideClob clob = (ClientSideClob) obj;
        
        StringWriter stringWriter = new StringWriter();
        Reader reader = clob.getCharacterStream();
        BufferedReader bufferedReader = new BufferedReader(reader);
        char[] cbuf = new char[1024];
        int l = 0;
        while ((l = bufferedReader.read(cbuf)) > 0) {
          stringWriter.write(cbuf, 0, l);
        }
        
        return createUnicodeBuilder().appendUnicode(stringWriter.toString());
      } catch (Exception e) {
        log.log(Level.SEVERE, "Failed to read ClientSideClob", e);
        return NullValue.NULL;
      }
    }
    
    return super.wrapJava(obj);
  }

}
